<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box1 {
        width: 100px;
        height: 100px;
        background-color: red;
        position: absolute;
      }
      #box2 {
        width: 100px;
        height: 100px;
        background-color: yellow;
        position: absolute;

        left: 20px;
        height: 100px;
      }
    </style>
    <script>
      window.onload = function () {
        /**
         * 拖拽box1元素
         *  拖拽的流程
         *   1.当鼠标在被拖拽元素上按下，开始拖拽 onmousedown
         *   2.当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove
         *   3.当鼠标松开时，被拖拽元素固定在当前位置 onmouseup
         */
        var box1 = document.getElementById("box1");
        box1.onmousedown = function (event) {
          // div的偏移量 鼠标.clentX -元素.offsetleft
          // div的偏移量 鼠标.clentY -元素.offsettop
          var ol = event.clientX - box1.offsetLeft;
          var ot = event.clientY - box1.offsetTop;
          document.onmousemove = function (event) {
            var left = event.clientX - ol;
            var top = event.clientY - ot;

            box1.style.left = left + "px";
            box1.style.top = top + "px";
          };
          //   被拖拽元素固定在当前位置 onmouseup
          document.onmouseup = function () {
            document.onmousemove = null;
            document.onmouseup = null;
          };
          /**
           * 当我们拖拽一个网页中的内容时，浏览器会默认去搜索引擎中搜索内容，
           *  此时会导致拖拽功能的异常，这是浏览器提供的默认行为
           * 可以通过 return false来取消默认行为
           *
           *
           */
          return false;
        };
      };
    </script>
  </head>
  <body>
    <div id="box1"></div>
    <div id="box2"></div>
  </body>
</html>
